//
//  JWTRegisterViewController.m
//  JWT
//
//  Created by Apple on 2017/1/1.
//  Copyright © 2017年 com.jwtsoft. All rights reserved.
//

#import "JWTRegisterViewController.h"
#import "JWTAppTabBarTheme.h"

#import "JWTLoginViewController.h"
#import "NSTimerBlock.h"


#define Margin 15
#define Layer_Color RGB(77,80,81)
#define HeaderBackground_Color RGB(246,0,188)
#define TextField_Color RGB(241,241,242)


@interface JWTRegisterViewController ()<UITextFieldDelegate>

@end

@implementation JWTRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//     [[JWTAppTabBarTheme sharedInstance] customizeInterfaceUIColor:HeaderBackground_Color];
//    UINavigationBar *navBarAppearance = [UINavigationBar appearance];
//    UIImage *backgroundImage = nil;
//    backgroundImage =[JWTCommons imageWithColor:HeaderBackground_Color size:(CGSizeMake(UISCREEN_WIDTH, 64.0f))];
//
////    [navBarAppearance setBackgroundImage:backgroundImage
////                           forBarMetrics:UIBarMetricsCompact];
//    [self.navigationController.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsCompact];
//    UINavigationBar *bar = [UINavigationBar appearance];
//    bar.barTintColor = HeaderBackground_Color;
//    //设置字体颜色
//    bar.tintColor = HeaderBackground_Color;
//    [bar setTitleTextAttributes:@{NSForegroundColorAttributeName :HeaderBackground_Color}];

    //初始化视图
    [self initWithView];
}

-(void) initWithView{
    WS(weakSelf);
    _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.left, self.view.top-1, UISCREEN_WIDTH, (UISCREEN_HEIGHT-64)*0.35)];
    [_headerImageView setImage:[UIImage imageNamed:@"HeaderBackGround_Regist"]];
    [self.view addSubview:_headerImageView];
    
    //注册手机号
    _resPhoneTextField = [[JWTTextField alloc] initWithFrame:CGRectMake(UISCREEN_WIDTH*0.15, _headerImageView.bottom+Margin, UISCREEN_WIDTH*0.7, 50)];
    _resPhoneTextField.layer.borderWidth = 0.5f;
    _resPhoneTextField.layer.cornerRadius = _resPhoneTextField.height * 0.5;
    _resPhoneTextField.layer.borderColor = Layer_Color.CGColor;
    _resPhoneTextField.clearButtonMode = UITextFieldViewModeAlways;
    _resPhoneTextField.delegate = self;
    _resPhoneTextField.placeholder = @"请输入手机号";
    [self.view addSubview:_resPhoneTextField];
    
    UIImageView *rephoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Margin, 8, 30, 30)];
    [rephoneImageView setImage:[UIImage imageNamed:@"Phone"]];
    rephoneImageView.contentMode = UIViewContentModeScaleAspectFit;
    rephoneImageView.layer.masksToBounds = YES;
    _resPhoneTextField.leftViewMode=UITextFieldViewModeAlways;
    _resPhoneTextField.leftView.frame = CGRectMake(Margin, 8, 34, 34);
    _resPhoneTextField.leftView = rephoneImageView;
    
    //验证码
    _resVerifyTextField = [[JWTTextField alloc] initWithFrame:CGRectMake(UISCREEN_WIDTH*0.15, _resPhoneTextField.bottom+Margin, UISCREEN_WIDTH*0.7*0.65, 50)];
    _resVerifyTextField.layer.borderWidth = 0.5f;
    _resVerifyTextField.layer.cornerRadius = _resPhoneTextField.height * 0.5;
    _resVerifyTextField.layer.borderColor = Layer_Color.CGColor;
    _resVerifyTextField.placeholder = @"请输入验证码";
    _resVerifyTextField.font = Text_Font13;
    _resVerifyTextField.delegate = self;
    _resVerifyTextField.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:_resVerifyTextField];
    
    UIImageView *resVerifyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Margin, 8, 30, 30)];
    [resVerifyImageView setImage:[UIImage imageNamed:@"VerifyCode"]];
    resVerifyImageView.contentMode = UIViewContentModeScaleAspectFit;
    resVerifyImageView.layer.masksToBounds = YES;
    _resVerifyTextField.leftViewMode=UITextFieldViewModeAlways;
    _resVerifyTextField.leftView.frame = CGRectMake(Margin, 8, 34, 34);
    _resVerifyTextField.leftView = resVerifyImageView;
    
    //获取验证码按钮
    _getVerifyBtn = [[UIButton alloc] initWithFrame:CGRectMake(_resVerifyTextField.right+5, _resVerifyTextField.top+5, _resPhoneTextField.width-_resVerifyTextField.width-5, _resVerifyTextField.height-10)];
    [_getVerifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_getVerifyBtn setTitleColor:RGB_WhiteBackGround forState:UIControlStateNormal];
    [_getVerifyBtn setBackgroundColor:HeaderBackground_Color];
    _getVerifyBtn.titleLabel.font = Text_Font13;
    _getVerifyBtn.layer.cornerRadius = _getVerifyBtn.height * 0.5;
    _getVerifyBtn.layer.borderColor = Layer_Color.CGColor;
    [self.view addSubview:_getVerifyBtn];
    
    //获取短信验证码
    [_getVerifyBtn addButtonBlockControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [weakSelf getVerifyCodeWithActionRegisterWithBtn:sender];
    }];
    
    //密码
    _resPassWordTextField = [[JWTTextField alloc] initWithFrame:CGRectMake(UISCREEN_WIDTH*0.15, _resVerifyTextField.bottom+Margin, UISCREEN_WIDTH*0.7, 50)];
    _resPassWordTextField.layer.borderWidth = 0.5f;
    _resPassWordTextField.layer.cornerRadius = _resPassWordTextField.height * 0.5;
    _resPassWordTextField.layer.borderColor = Layer_Color.CGColor;
    _resPassWordTextField.placeholder = @"请输入密码";
    _resPassWordTextField.secureTextEntry = YES;
    _resPassWordTextField.delegate = self;
    _resPassWordTextField.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:_resPassWordTextField];
    
    UIImageView *resPassWordImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Margin, 8, 30, 30)];
    [resPassWordImageView setImage:[UIImage imageNamed:@"PassWord"]];
    resPassWordImageView.contentMode = UIViewContentModeScaleAspectFit;
    resPassWordImageView.layer.masksToBounds = YES;
    _resPassWordTextField.leftViewMode=UITextFieldViewModeAlways;
    _resPassWordTextField.leftView.frame = CGRectMake(Margin, 8, 34, 34);
    _resPassWordTextField.leftView = resPassWordImageView;
    
    //注册
    _registBtn = [[UIButton alloc] initWithFrame:CGRectMake(UISCREEN_WIDTH*0.25, _resPassWordTextField.bottom+Margin*2, UISCREEN_WIDTH*0.5, 50)];
    _registBtn.layer.borderWidth = 0.5f;
    _registBtn.layer.cornerRadius = _resPassWordTextField.height * 0.5;
    _registBtn.layer.borderColor = Layer_Color.CGColor;
    [_registBtn setTitle:@"注 册" forState:UIControlStateNormal];
    [_registBtn setTitleColor:RGB_WhiteBackGround forState:UIControlStateNormal];
    [_registBtn setBackgroundColor:HeaderBackground_Color];
    [self.view addSubview:_registBtn];
    
    
    //注册页面跳转
    [_registBtn addButtonBlockControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [weakSelf userTelPhoneWithActionRegist];
    }];
    
    //已有账号
    _markWordLabel = [[UILabel alloc] initWithFrame:CGRectMake(_registBtn.left, _registBtn.bottom+2*Margin, _registBtn.width*0.6, 34)];
    _markWordLabel.textAlignment = NSTextAlignmentRight;
    _markWordLabel.text = @"已经有账号?";
    _markWordLabel.font = Text_Font13;
    [self.view addSubview:_markWordLabel];
    
    _loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(_markWordLabel.right+5, _markWordLabel.top, _registBtn.width*0.4-5,_markWordLabel.height)];
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [_loginBtn setTitleColor:HeaderBackground_Color forState:UIControlStateNormal];
    _loginBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _loginBtn.titleLabel.font = Text_Font14;
    [self.view addSubview:_loginBtn];
    
    
    //登录页面跳转
    [_loginBtn addButtonBlockControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    
}

//获取短信验证码
-(void) getVerifyCodeWithActionRegisterWithBtn:(UIButton *)sender{
    //1.手机号不能为空
    if ([_resPhoneTextField.text isEqualToString:@""]) {
        [HUD showToast:@"请输入手机号"];
        return;
        
    }else if ([[JWTCommons sharedInstance] validateMobile:_resPhoneTextField.text] == 0){
        [HUD showToast:@"手机号格式不正确"];
        return;
    }else{
        [_resPhoneTextField resignFirstResponder];
        //点击按钮获取验证码接口
        NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getVerifyCodeWithActionRegisterWithTel:_resPhoneTextField.text andType:@"0"];
        [AFNHttpsRequest requestWithUrl:urlString WithParam:nil WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
            [HUD hideUIBlockingIndicator];
            NSLog(@"%@",model);
            if (model) {
                //code：200-请求成功，0-请求失败，400-非法ip访问，406-手机格式不正确，4030-手机号被列入黑名单，1-（type=0，用户已注册；type=1，用户不存在
                if ([[model objectForKey:@"code"] integerValue] == 200) {
                    [HUD showToast:GetVerifyCode_Success];
                    //创建定时器计时
                    ((UIButton *)sender).enabled = NO;
                    __block NSInteger timersec = 60;
                    __block NSTimerBlock *timer = [NSTimerBlock scheduledTimerWithTimeInterval:1.0 scheduledBlock:^(NSTimerBlock *aTimer)
                                                   {
                                                       timersec--;
                                                       NSLog(@"timersec=%ld",(long)timersec);
                                                       if(timersec <=0)
                                                       {
                                                           ((UIButton *)sender).enabled = YES;
                                                           [timer invalidate];
                                                       }
                                                       else
                                                       {
                                                           [((UIButton *)sender) setTitle:[NSString stringWithFormat:@"%ld秒",timersec] forState:UIControlStateDisabled];
                                                       }
                                                       
                                                   }];
                }else{
                    [HUD showToast:[model objectForKey:@"message"]];
                }
            }
        }];
    }
}



//用户注册
-(void) userTelPhoneWithActionRegist{
    if ([self.resPhoneTextField.text isEqualToString:@""]) {
        [HUD showToast:@"手机号不能空"];
        return ;
    }else if ([[JWTCommons sharedInstance] validateMobile:_resPhoneTextField.text] == 0){
        [HUD showToast:@"手机号格式不正确"];
        return;
    }
    
    if ([self.resVerifyTextField.text isEqualToString:@""]) {
        [HUD showToast:@"验证码不能为空"];
        return ;
    }
    
    if ([self.resPassWordTextField.text isEqualToString:@""]) {
        [HUD showToast:@"密码不能为空"];
        return;
    }else{
        if (self.resPassWordTextField.text.length < 6) {
            [HUD showToast:@"密码长度不小于6位"];
            return;
        }
    }
    
    
    [HUD showUIBlockingIndicator];
    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getHttpsUrlWithActionRegister];
    
    NSDictionary *dict = @{@"tel":_resPhoneTextField.text,@"password":[NSString md5:_resPassWordTextField.text],@"telcode":_resVerifyTextField.text};
    
    [AFNHttpsRequest requestWithUrl:urlString WithParam:dict WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
        [HUD hideUIBlockingIndicator];
        [self resignFirstResponseAction];
        NSLog(@"%@",model);
        if (model) {
            [HUD showToast:[model objectForKey:@"message"]];
            if ([[model objectForKey:@"code"] integerValue] == 200) {
                APPDELEGATE.userInfo = [JWTUserInfo mj_objectWithKeyValues:[model objectForKey:@"data"]];
                //判断是否记住密码与自动登录
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:APPDELEGATE.userInfo.name forKey:@"userName"];
                [userDefaults setObject:APPDELEGATE.userInfo.tokenid forKey:@"tokenID"];
                [userDefaults synchronize];
                APPDELEGATE.userInfo = [[JWTUserInfo alloc] init];
                APPDELEGATE.userInfo.tel = _resPhoneTextField.text;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Add_UserPhoneTextAction" object:nil];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else{
                [HUD showToast:[model objectForKey:@"message"]];
            }
        }
    }];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    CGFloat offset = self.view.frame.size.height - (textField.frame.origin.y+textField.frame.size.height+216+50);
    if (offset <= 0) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.view.frame;
            frame.origin.y = offset;
            self.view.frame = frame;
        }];
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = self.view.frame;
        frame.origin.y = 64.0;
        self.view.frame = frame;
    }];
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self resignFirstResponseAction];
}

-(void)navBack{
    [super navBack];
    [self resignFirstResponseAction];
}

-(void) resignFirstResponseAction{
    [_resPhoneTextField resignFirstResponder];
    [_resVerifyTextField resignFirstResponder];
    [_resPassWordTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
